package com.ruoyi.tranShort.mqtt;

import com.alibaba.fastjson.JSONObject;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.spring.SpringUtils;
import com.ruoyi.mqtt.api.receive.ReceiveMessage;
import com.ruoyi.tranShort.mqtt.api.WristletWriteBackCallBack;
import com.ruoyi.tranShort.mqtt.common.constants.MqttRedisKey;
import com.ruoyi.tranShort.mqtt.common.constants.ResponseConstants;
import com.ruoyi.tranShort.mqtt.common.constants.TypeConstants;
import org.eclipse.paho.client.mqttv3.IMqttDeliveryToken;
import org.eclipse.paho.client.mqttv3.MqttMessage;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author wwy
 * @date 2021-08-10 8:58
 */
public class Subscribe implements ReceiveMessage {
    /**
     * 消息透传返回消息集合
     */
    public static Map<String,String> passthroughMap = new HashMap<>();
    /**
     * 设备连接数据返回集合
     */
    public static Map<String,String> connectMap = new HashMap<>();
    /**
     * 关闭连接数据返回集合
     */
    public static Map<String,String> closeMap = new HashMap<>();

    private RedisCache redisCache = SpringUtils.getBean(RedisCache.class);
    /**
     * 叫哨回复回调函数
     */
    public static WristletWriteBackCallBack wristletWriteBackCallBack;

    @Override
    public void connectionLost(Throwable cause) {

    }

    @Override
    public void messageArrived(String topic, MqttMessage message) throws Exception {
        String baseMessage = new String(message.getPayload());

        //内容解析
        JSONObject parseObject = JSONObject.parseObject(baseMessage).getJSONObject("comType");
        //{ "comType": { "type": "Up", "msgId": "252", "clientId": "8CD4950012B9", "content": { "type": "ConnectDeviceLong", "data": { "response": "Ok", "mac": "E61F0BD7BCAF" } } } }
        String type = parseObject.getString("type");
        JSONObject content = parseObject.getJSONObject("content");
        //网关mac地址
        String clientId = parseObject.getString("clientId");
        //不是上行的数据，不进行处理
        if(!TypeConstants.UP.equals(type)){
           return;
        }
        //响应结果类型判断
        String contentType = content.getString("type");
        JSONObject data = content.getJSONObject("data");
        String response = data.getString("response");
        String mac = data.getString("mac");
        String data1 = data.getString("data");
        switch (contentType){
            case TypeConstants.CONNECT_DEVICE_LONG:
                //长连接响应
                connectMap.put(mac,response);
                break;
            case TypeConstants.PASSTHROUGH:
                //消息透传

                switch (response){
                    case ResponseConstants.REPLAY:
                        //消息透传回答
                        //把最终响应数据按设备mac地址进行保存
                        passthroughMap.put(mac,data1);
                        break;
                    default:
                        break;
                }
                break;
            case TypeConstants.DISCONNECT_DEVICE:
                //关闭连接响应
                closeMap.put(mac,response);
                break;
            case TypeConstants.REPORT_BORDCAST:
                //处理广播数据
                String numberStr = data.getString("number");
                int number = Integer.parseInt(numberStr);
                //循环获取值,保存设备与网关的信号强度
                for (int i = 1; i <= number; i++) {
                    //设备mac地址
                    String macStr = data.getString("mac" + i);
                    String rssiStr = data.getString("rssi" + i);
                    String key = MqttRedisKey.LOCATIONTRACKING+macStr;
                    redisCache.setCacheMapValue(key,clientId,rssiStr);
                    redisCache.expire(key,3, TimeUnit.SECONDS);

                    //解析内容
                    String detailStr = data.getString("pack" + i).replaceAll("(.*FFB8)", "");
                    //（00代表正常、02呼叫、03呼叫+防拆、04报警、05报警+防拆、06报警+呼叫、07拆开+呼叫+报警）
                    String warning = detailStr.substring(10, 12);

                    //判断是否为叫哨回复信息
                    if("02".equals(warning) || "04".equals(warning) || "06".equals(warning)){
                         //执行回调
                        if(wristletWriteBackCallBack != null){
                            wristletWriteBackCallBack.invoke(mac);
                        }
                    }
                }


                break;
            default:
                break;
        }


    }

    @Override
    public void deliveryComplete(IMqttDeliveryToken token) {

    }
}
